package com.example.baseapp.activity.Fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.baseapp.R
import com.example.baseapp.network.NetService
import com.example.baseapp.topmethod.ServerCreate
import com.example.baseapp.topmethod.huaCoAwait
import kotlinx.android.synthetic.main.fragment_coroutine.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import retrofit2.await

/**
 * @作者：HuaCon
 *
 * @类描述：retrofit 使用协程请求网络
 *
 */
private const val TAG = "CoroutineFragment"

class CoroutineFragment : Fragment() {


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_coroutine, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        bt_request.setOnClickListener {
            GlobalScope.launch(Dispatchers.Main) {
                tv_display.text = getNewsTop()
            }

        }
    }

    private suspend fun getNewsTop(): String {
        val list = ServerCreate.create<NetService>()
            .getNewsTop(appKey = "3eb65fc6c4445d6596887377c51fa5f2").huaCoAwait()
        return list?.result?.data.toString()
    }

}